package main

import (
	"gopkg.in/mgo.v2"
	"log"
	"spirit/mongodb"
	"spirit/utils"
	"strconv"
	"strings"
	"testing"
)

func Test_dealData(t *testing.T) {
	mongodb.InitMongodbPool(5, "mongodb://screen:screen20190901@119.29.156.83:17081/screening", "screening")
	queryMap := map[string]interface{}{}
	totalCount := mongodb.Count("infoCollection", queryMap)
	totalPage := (totalCount + 50 - 1) / 50
	log.Printf("共有数据[%d]条,[%d页]", totalCount, totalPage)
	if totalPage > 0 {
		allPage := totalPage                //总页数
		allThread := 10                     //总共要启动的线程数
		everyPage := allPage / allThread    //每个线程要处理的页数
		everyPageAdd := allPage % allThread //前几个线程要增加一页
		startPage := 0
		endPage := 0 //开始页数和结束页数（从下标0开始）
		flag := 0    //偏移量
		for page := 0; page < 10; page++ {
			if page == 0 {
				startPage = 0
			} else {
				startPage = endPage + 1
			}
			if page < everyPageAdd {
				endPage = (page+1)*everyPage + flag
				flag++
			} else {
				endPage = (page+1)*everyPage + flag - 1
			}
			go func(clientNum, startP, endP int) {
				log.Printf("启动线程 :[%d ]startPage[%d]---endPage[%d]", clientNum, startP, endP)
				for i := startP; i <= endP; i++ {
					if i == 1 || i == 107 {
						start := (i - 1) * 50
						log.Printf("线程【%d】start:[%d]", clientNum, start)
					}

					/*data := mongodb.Find("infoCollection", queryMap, `{"_id":-1}`, nil, false, start, 50)
					for _, val := range *data {
						id := utils.BsonIdToSId(val["_id"])
						var _ccRiskRating map[string]interface{}
						ccRiskRating := val["ccRiskRating"]
						if ccRiskRating != nil {
							_ccRiskRating = ccRiskRating.(map[string]interface{})
						} else {
							_ccRiskRating = make(map[string]interface{}, 0)
						}

						livingStatus := val["livingStatus"]
						if livingStatus != nil {
							_livingStatus := livingStatus.(map[string]interface{})
							dealLivingStatus(_livingStatus, _ccRiskRating)
						}

						family := val["family"]
						if family != nil {
							_family := family.(map[string]interface{})
							dealFamily(_family, _ccRiskRating)
						}

						pastMedicalHistory := val["pastMedicalHistory"]
						if pastMedicalHistory != nil {
							_pastMedicalHistory := pastMedicalHistory.(map[string]interface{})
							dealPastMedicalHistoryUpdateData(_pastMedicalHistory, _ccRiskRating)
						}

						physicalCheckup := val["physicalCheckup"]
						if physicalCheckup != nil {
							_physicalCheckup := physicalCheckup.(map[string]interface{})
							dealPhysicalCheckup(_physicalCheckup, _ccRiskRating)
						}
						ccRiskRatingDeal(_ccRiskRating)
						val["ccRiskRating"] = _ccRiskRating
						b := mongodb.UpdateById("infoCollection", id, val)
						if b {

						} else {
							log.Printf("id:[%s]更新失败", id)
						}
					}*/
					//log.Printf("已处理【%d】条", start+50)
					//log.Printf("当前第[%d]页,第一个人:[%s],最后一个人[%s]", i, data1["userName"], data2["userName"])
				}
			}(page, startPage+1, endPage+1)

		}
		b := make(chan bool)
		<-b
	}

}

func Test_dealData2(t *testing.T) {
	mongodb.InitMongodbPool(10, "mongodb://screen:screen20190901@119.29.156.83:17081/screening", "screening")
	queryMap := map[string]interface{}{}
	sess := mongodb.GetMgoConn()
	defer mongodb.DestoryMongoConn(sess)
	it := sess.DB("screening").C("infoCollection").Find(queryMap).Sort("-_id").Iter()
	num := 0
	for m := map[string]interface{}{}; it.Next(&m); {
		//log.Println(m)
		if dealData(m, sess) {
			num++
			log.Printf("成功更新[%d]条", num)
		} else {
			log.Println("cuocucuo")
		}
	}

}

func Test_dealData3(t *testing.T) {
	allPage := 117                      //总页数
	allThread := 10                     //总共要启动的线程数
	everyPage := allPage / allThread    //每个线程要处理的页数
	everyPageAdd := allPage % allThread //前几个线程要增加一页
	startPage := 0
	endPage := 0 //开始页数和结束页数（从下标0开始）
	flag := 0    //偏移量
	for page := 0; page < 10; page++ {
		if page == 0 {
			startPage = 0
		} else {
			startPage = endPage + 1
		}
		if page < everyPageAdd {
			endPage = (page+1)*everyPage + flag
			flag++
		} else {
			endPage = (page+1)*everyPage + flag - 1
		}
		log.Printf("startPage[%d]---endPage[%d]", startPage+1, endPage+1)
	}

	b := make(chan bool)
	<-b

}
func dealData(val map[string]interface{}, sess *mgo.Session) bool {
	id := utils.BsonIdToSId(val["_id"])
	var _ccRiskRating map[string]interface{}
	ccRiskRating := val["ccRiskRating"]
	if ccRiskRating != nil {
		_ccRiskRating = ccRiskRating.(map[string]interface{})
	} else {
		_ccRiskRating = make(map[string]interface{}, 0)
	}
	livingStatus := val["livingStatus"]
	if livingStatus != nil {
		_livingStatus := livingStatus.(map[string]interface{})
		dealLivingStatus(_livingStatus, _ccRiskRating)
	}

	family := val["family"]
	if family != nil {
		_family := family.(map[string]interface{})
		dealFamily(_family, _ccRiskRating)
	}

	pastMedicalHistory := val["pastMedicalHistory"]
	if pastMedicalHistory != nil {
		_pastMedicalHistory := pastMedicalHistory.(map[string]interface{})
		dealPastMedicalHistoryUpdateData(_pastMedicalHistory, _ccRiskRating)
	}

	physicalCheckup := val["physicalCheckup"]
	if physicalCheckup != nil {
		_physicalCheckup := physicalCheckup.(map[string]interface{})
		dealPhysicalCheckup(_physicalCheckup, _ccRiskRating)
	}
	ccRiskRatingDeal(_ccRiskRating)
	val["ccRiskRating"] = _ccRiskRating
	/*if err := sess.DB("screening").C("infoCollection").Update(bson.M{"_id": utils.StringTOBsonId(id)}, val); err != nil {
		log.Printf("id:[%s]更新失败", id)
	} else {
		return true
	}*/
	b := mongodb.UpdateById("infoCollection", id, val)
	if b {
		return true
	} else {
		log.Println("更新出错...")
	}
	return false
}

func ccRiskRatingDeal(ccRiskRatingData map[string]interface{}) {
	var risk_number = 0
	for key, val := range ccRiskRatingData {
		if ((key != "fengxianpingji_naocuzhong_history" && key != "fengxianpingji_TIA_history") && (val == "有" || val == "是")) {
			risk_number++
		}
	}
	if (ccRiskRatingData["fengxianpingji_naocuzhong_history"] == "有" || ccRiskRatingData["fengxianpingji_TIA_history"] == "有") {
		ccRiskRatingData["risk_level"] = "高危"
		ccRiskRatingData["risk_reason"] = "有脑卒中或者TIA"
	} else if (risk_number >= 3) {
		ccRiskRatingData["risk_level"] = "高危"
		ccRiskRatingData["risk_reason"] = "患有除脑卒中和TIA之外的其他危险因素项目数量大于等于3"
	} else if (risk_number < 3) {
		if (ccRiskRatingData["fengxianpingji_gaoxueya"] == "有" || ccRiskRatingData["fengxianpingji_tnb"] == "有" || ccRiskRatingData["fengxianpingji_fc"] == "有") {
			ccRiskRatingData["risk_level"] = "中危"
			ccRiskRatingData["risk_reason"] = "有高血压、糖尿病、房颤或者瓣膜性心脏病三种慢性病之一"
		} else {
			ccRiskRatingData["risk_level"] = "低危"
			ccRiskRatingData["risk_reason"] = "具有三项以下危险因素且无高血压、糖尿病、心房颤动或者瓣膜性心脏病等慢性疾病"
		}
	}
}

func dealPhysicalCheckup(physicalCheckup map[string]interface{}, _ccRiskRating map[string]interface{}) {
	if physicalCheckup["tigejiancha_bmi"] != "" {
		_bmi, _ := strconv.ParseFloat(physicalCheckup["tigejiancha_bmi"].(string), 32)
		if _bmi >= 28.0 {
			//log.Printf("超重,设置ccRiskRating")
			_ccRiskRating["fengxianpingji_chaozhong"] = "是"
			//log.Printf("_ccRiskRating['fengxianpingji_chaozhong']设置[是]成功......")
		} else {
			_ccRiskRating["fengxianpingji_chaozhong"] = "否"
		}
	}
}

func dealPastMedicalHistoryUpdateData(_pastMedicalHistoryData map[string]interface{}, _ccRiskRating map[string]interface{}) {
	if _pastMedicalHistoryData["gaoxueya"].(string) == "有" {
		//log.Printf("有高血压,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_gaoxueya"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_gaoxueya']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_gaoxueya"] = "无"
	}

	if _pastMedicalHistoryData["xzyc"].(string) == "有" {
		//log.Printf("有血脂异常,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_xzyc"] = "是"
		//log.Printf("_ccRiskRating['fengxianpingji_xzyc']设置[是]成功......")
	} else {
		_ccRiskRating["fengxianpingji_xzyc"] = "否"
	}
	if _pastMedicalHistoryData["tnb"].(string) == "有" {
		//log.Printf("有糖尿病,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_tnb"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_tnb']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_tnb"] = "无"
	}

	if _pastMedicalHistoryData["xinzangbing"].(string) == "有" && strings.Index(_pastMedicalHistoryData["xinzangbing_leixing"].(string), "房颤") > -1 {
		//log.Printf("有心脏病类型是房颤,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_fc"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_fc']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_fc"] = "无"
	}
	if _pastMedicalHistoryData["naocuzhong"].(string) == "有" {
		//log.Printf("有既往脑卒中,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_naocuzhong_history"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_naocuzhong_history']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_naocuzhong_history"] = "无"
	}
	if _pastMedicalHistoryData["naoquexue"].(string) == "有" {
		//log.Printf("有既往TIA,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_TIA_history"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_TIA_history']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_TIA_history"] = "无"
	}
}

func dealFamily(family map[string]interface{}, _ccRiskRating map[string]interface{}) {
	if family["jiazushi_zhongfeng"] == "有" {
		//log.Printf("有脑卒中家族史,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_naocuzhong_family_history"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_naocuzhong_family_history']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_naocuzhong_family_history"] = "无"
	}
}

func dealLivingStatus(livingStatus map[string]interface{}, _ccRiskRating map[string]interface{}) {
	if livingStatus["isSmoking"] == "是" {
		//log.Printf("有吸烟史,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_xiyan"] = "有"
		//log.Printf("_ccRiskRating['fengxianpingji_xiyan']设置[有]成功......")
	} else {
		_ccRiskRating["fengxianpingji_xiyan"] = "无"
	}
	if livingStatus ["sportStatus"] == "缺乏运动" {
		//log.Printf("运动缺乏,设置ccRiskRating")
		_ccRiskRating["fengxianpingji_yundong"] = "是"
		//log.Printf("_ccRiskRating['fengxianpingji_yundong']设置[是]成功......")
	} else {
		_ccRiskRating["fengxianpingji_yundong"] = "否"
	}
}
